var tcity = require("../../utils/citys");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isEdit: true, // false为正处于编辑状态  true为未处于编辑状态
    isCheckedAll: false, // 当前购物车商品是否全选
    goods_show_list: [], // 当前用户下购物车商品数据
    totalPrice: 0, // 当前总价
    payNum: 0, // 结算的商品个数
    showAddressPanel: false, // false为隐藏地址面板，true为显示
    address_List: [], // 用户地址列表
    address_current: {} // 用户当前地址
  },

  // 初始化页面
  initPage() {
    // 获取购物车商品数据
    wx.request({
      url: 'http://api_devs.wanxikeji.cn/api/shoppingCarList',
      data: {
        "token":wx.getStorageSync('token')
      },
      success: ((res) => {
        console.log(res);
        console.log(res.data.data.data);
        let tem_data = res.data.data.data;
        for (let i = 0; i < tem_data.length; i++) {
          tem_data[i].isChecked = false;
        }
        this.setData({
          goods_show_list: tem_data
        })
        // console.log(this.data.goods_show_list);
      }),
      fail: ((err) => {
        console.log(err);
      })
    })

    // 获取用户地址信息
    wx.request({
      url: 'http://api_devs.wanxikeji.cn/api/userAddressList',
      data: {
        "token":wx.getStorageSync('token')
      },
      success: (res) => {
        console.log(res.data.data);
        // 整理返回的数据
        tcity.init(this);
        var cityData = this.data.cityData;
        var tempList=[];
        for(let i = 0; i < res.data.data.length; i++){
          let obj={};
          let temp1="";
          let temp2="";
          let temp3="";
          let temp4="";

          //筛选省
          temp1=cityData.filter((value)=>{
            if(value.code==res.data.data[i].procince) 
            return value;
          })[0];
          //筛选市
          temp2=(temp1.sub).filter((value)=>{
            if(value.code==res.data.data[i].city) 
            return value;
          })[0];
          //筛选区
          temp3=(temp2.sub).filter((value)=>{
            if(value.code==res.data.data[i].area) 
            return value;
          })[0];
        
          temp4=res.data.data[i].detailed;

          obj["address_id"]=res.data.data[i].address_id;
          obj["area"]=temp3.name;
          obj["city"]=temp2.name;
          obj["procince"]=temp1.name;
          obj["area_number"]=res.data.data[i].area;
          obj["city_number"]=res.data.data[i].city;
          obj["procince_number"]=res.data.data[i].procince;
          obj['created_time']=res.data.data[i].created_time;
          obj["default"]=res.data.data[i].default;
          obj["detailed"]=res.data.data[i].detailed;
          obj["name"]=res.data.data[i].name;
          obj["phone"]=res.data.data[i].phone;
          obj["status"]=res.data.data[i].status;
          obj["address"]=temp1.name+'-'+temp2.name+'-'+temp3.name+'-'+temp4;
          if (res.data.data[i].default == 1) {
            obj['isChecked']=true;
          } else {
            obj['isChecked']=false
          }
          tempList.push(obj);
        }
        // 整理完毕，赋值到变量中
        this.setData({
          address_List: tempList
        })
        this.change_address_current(); // 确认用户当前选择的地址
        console.log(this.data.address_List);
      },
      fail: (res) => {
        console.log(res);
      }
    })

    // wx.request({
    //   url: 'http://api_devs.wanxikeji.cn/api/shoppingCarAddModify',
    //   data: {
    //     "token":"9df0ddfc9588c3917606049f4dcd6a67",
    //     "good_id":1140,
    //     "num":2,
    //     "price":1000.00,
    //     "money":1000.00,
    //     "sku":'{"颜色":"红色","价格":"1000"}'
    //     },
    //     success: ((res) => {
    //       console.log(res);
    //     }),
    //     fail: ((err) => {
    //       console.log(err);
    //     })
    // })

    // wx.request({
    //   url: 'http://api_devs.wanxikeji.cn/api/shoppingCarDelete',
    //   data: {
    //     "token":"9df0ddfc9588c3917606049f4dcd6a67",
    //     "shopping_car_id":"1744"
    //     },
    //     success: ((res) => {
    //       console.log(res);
    //     }),
    //     fail: ((err) => {
    //       console.log(err);
    //     })
    // })
  },

  // 用户地址面板显示与隐藏
  change_address_display(e) {
    if (e.currentTarget.dataset.btn != undefined) {
      this.setData({
        showAddressPanel: false
      })
    } else {
      this.setData({
        showAddressPanel: true
      })
    }
  },
  // 修改用户地址（单选）
  change_address(e) {
    let idx = e.currentTarget.dataset.idx;
    let tem = JSON.parse(JSON.stringify(this.data.address_List));
    for (let i = 0; i < tem.length; i++) {
      tem[i].isChecked = false;
    }
    tem[idx].isChecked = true;
    this.setData({
      address_List: tem
    })
    this.change_address_current(); // 确认用户当前选择的地址
  },
  // 修改当前用户选择地址
  change_address_current() {
    for (let i = 0; i < this.data.address_List.length; i++) {
      if (this.data.address_List[i].isChecked) {
        this.setData({
          address_current: JSON.parse(JSON.stringify(this.data.address_List[i]))
        })
      }
    }
    console.log(this.data.address_current);
  },
  // 点击编辑执行函数
  edit() {
    this.setData({
      isEdit: !this.data.isEdit
    })
  },
  // 选择一个购物车商品
  check_one(e) {
    // console.log(e.currentTarget.dataset.idx);
    let idx = e.currentTarget.dataset.idx;
    let tem = JSON.parse(JSON.stringify(this.data.goods_show_list));
    tem[idx].isChecked = !tem[idx].isChecked;
    // 判断是否已全选
    for (let i = 0; i < tem.length; i++) {
      if (!tem[i].isChecked) {
        this.setData({
          isCheckedAll: false
        })
        break;
      } else {
        if (i == tem.length - 1) {
          this.setData({
            isCheckedAll: true
          })
        }
      }
    }
    this.setData({
      goods_show_list: tem
    })
    this.setTotalPrice(); // 重新计算总价
    this.pay_goods_Num(); // 计算结算商品个数
    console.log(this.data.goods_show_list);
  },
  // 全选购物车商品
  check_all() {
    let tem = JSON.parse(JSON.stringify(this.data.goods_show_list));
    for (let i = 0; i < tem.length; i++) {
      tem[i].isChecked = !this.data.isCheckedAll;
    }
    this.setData({
      goods_show_list: tem,
      isCheckedAll: !this.data.isCheckedAll
    })
    this.setTotalPrice(); // 重新计算总价
    this.pay_goods_Num(); // 计算结算商品个数
  },
  // 新增商品个数
  add_num(e) {
    console.log(e.currentTarget.dataset);
    let tem = JSON.parse(JSON.stringify(this.data.goods_show_list));
    let idx = e.currentTarget.dataset.idx;
    let num = e.currentTarget.dataset.num;
    num++;
    tem[idx].num = num
    this.setData({
      goods_show_list: tem
    })
    this.setTotalPrice(); // 重新计算总价
  },
  // 减少商品个数
  reduce_num(e) {
    console.log(e.currentTarget.dataset);
    let tem = JSON.parse(JSON.stringify(this.data.goods_show_list));
    let idx = e.currentTarget.dataset.idx;
    let num = e.currentTarget.dataset.num;
    if (num > 1) {
      num--;
    }
    tem[idx].num = num
    this.setData({
      goods_show_list: tem
    })
    this.setTotalPrice(); // 重新计算总价
  },
  // 手动输入商品数量
  change_num(e) {
    let tem = JSON.parse(JSON.stringify(this.data.goods_show_list));
    let idx = e.currentTarget.dataset.idx;
    let val = e.detail.value;
    if (val - 0 < 1) {
      val = 1;
      tem[idx].num = val
      this.setData({
        goods_show_list: tem
      })
      this.setTotalPrice(); // 重新计算总价
    } else {
      tem[idx].num = val
      this.setData({
        goods_show_list: tem
      })
      this.setTotalPrice(); // 重新计算总价
    }
  },
  // 价格总计
  setTotalPrice() {
    let tem = 0;
    for (let i = 0; i < this.data.goods_show_list.length; i++) {
      if (this.data.goods_show_list[i].isChecked) {
        tem = tem + (this.data.goods_show_list[i].price - 0) * this.data.goods_show_list[i].num;
      }
    }
    this.setData({
      totalPrice: tem
    })
  },
  // 计算结算商品个数
  pay_goods_Num() {
    let tem = JSON.parse(JSON.stringify(this.data.goods_show_list));
    let num = 0;
    for (let i = 0; i < tem.length; i++) {
      if (tem[i].isChecked) {
        num++;
      }
    }
    this.setData({
      payNum: num
    })
  },
  // 判断是否允许结算，允许结算就跳转支付页面
  isAllow_pay() {
    if (this.data.payNum > 0) {
      console.log('允许结算');
      let address_id = this.data.address_current.address_id;
      let tem_arr = [];
      for (let i = 0; i < this.data.goods_show_list.length; i++) {
        if (this.data.goods_show_list[i].isChecked) {
          tem_arr.push(JSON.parse(JSON.stringify(this.data.goods_show_list[i])));
        }
      }
      let shopping_car_ids = JSON.stringify(tem_arr);
      let money = this.data.totalPrice;
      // console.log(address_id,shopping_car_ids,money);
      console.log(shopping_car_ids);
      wx.navigateTo({
        url: '../order/order?address_id=' + address_id + '&money=' + money + '&shopping_cars_ids=' + shopping_car_ids,
      })
    } else {
      console.log('不允许结算');
      wx.showToast({
        title: '还未选择商品！',
        duration: 2000,
        icon: 'error',
        mask: true,
      })
    }
  },
  // 删除购物车商品
  delete_goods() {
    if (this.data.payNum > 0) {
      wx.showModal({
        title: '确定要删除选中的' + this.data.payNum + '件商品吗？',
        confirmColor: '#f06',
        success: (res) => {
          console.log(res);
          if (res.confirm) {
            let tem = JSON.parse(JSON.stringify(this.data.goods_show_list));
          let tem_deleted_id = [];
          let tem_no_deleted = [];
          for (let i = 0; i < tem.length; i++) {
            if (tem[i].isChecked) {
              tem_deleted_id.push(tem[i].shopping_car_id);
            } else {
              tem_no_deleted.push(tem[i]);
            }
          }
          // console.log(tem_deleted_id);
          // console.log(tem_no_deleted);
            for (let i = 0; i < tem_deleted_id.length; i++) {
              wx.request({
                url: 'http://api_devs.wanxikeji.cn/api/shoppingCarDelete',
                data: {
                  "token":wx.getStorageSync('token'),
                  "shopping_car_id":tem_deleted_id[i] + ''
                  },
                  success: ((res) => {
                    // console.log(res);
                    wx.showToast({
                      title: '成功删除！',
                      duration: 2000,
                      icon: 'success',
                      mask: true,
                    })
                    this.setData({
                      goods_show_list: tem_no_deleted
                    })
                  }),
                  fail: ((err) => {
                    // console.log(err);
                    wx.showToast({
                      title: '删除失败！',
                      duration: 2000,
                      icon: 'error',
                      mask: true,
                    })
                    this.setData({
                      goods_show_list: tem
                    })
                  })
              })
            }
          } else {
            console.log('已取消删除！');
          }
        },
        fail: (res) => {
          console.log(res);
        }
      })
    } else {
      wx.showToast({
        title: '还未选择商品！',
        duration: 1000,
        icon: 'error',
        mask: true,
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('token') == '') {
      wx.showToast({
        title: '请登录',
        icon: 'error',
        success: (res) => {
          setTimeout(() => {
            wx.switchTab({
              url: '../usercenter/usercenter',
            })
          },2000);
        }
      });
    } else {
      this.initPage();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})